<template>
  <div class="app-container">
      <div class="custom-icon-text" style="margin-top: -15px">
        <div class="search-form" style="width: 100%">
          <div style="width: 60px;height: 60px;margin-left: 0px;margin-top: 0px"><el-button icon="el-icon-s-data" class="custom-button">总数<br><br>{{total}}</el-button></div>
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" style="margin-top: 10px" label-width="68px">
            <div style=" border-bottom: 1px solid #333;margin-bottom: 10px">
              <div style="margin-left: 450px;margin-top: -60px">
                <el-form-item prop="residentTypeId">
                  <el-input
                    style="width: 250px"
                    v-model="queryParams.resident"
                    placeholder="请输入姓名、证件号、手机号"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" style="margin-left: -11px"  @click="handleQuery"></el-button>
                  <el-button icon="el-icon-refresh" size="mini"@click="advancedSearch" >高级检索</el-button>
                  <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置条件</el-button>
                </el-form-item>
              </div>
            </div>
            <div v-if="isAdvancedSearch" style="width: 100%;margin-top: 5px">
              <el-form-item label="人员类型" prop="residentTypeId">
                <el-select v-model="queryParams.residentTypeId" placeholder="全部" clearable>
                  <el-option
                    v-for="dict in dict.type.personnel_category"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="小区名称" prop="plotId">
                <el-select v-model="queryParams.plotId" placeholder="请选择小区" clearable>
                  <el-option v-for="i in plotList" :key="i.id" :label="i.plotName" :value="i.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="身份标签" prop="identityTag">
                <el-select v-model="queryParams.identityTag" placeholder="全部" clearable>
                  <el-option
                    v-for="dict in dict.type.personnel_tag"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="户籍地址" prop="householdAddress">
                <el-input
                  v-model="queryParams.householdAddress"
                  placeholder="请输入户籍地址"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="年龄段" prop="householdAddress">
                <el-input style="width: 105px" v-model="queryParams.minAge" clearable placeholder="最小年龄"/>
                <el-input style="width: 105px" v-model="queryParams.maxAge" clearable placeholder="最大年龄"/>
              </el-form-item>
              <el-form-item label="性别">
                <el-radio-group v-model="queryParams.gender">
                  <el-radio v-for="dict in dict.type.sys_user_sex"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value">
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:residents:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:residents:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:residents:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:residents:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="residentsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" width="50">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.$index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="人脸照片" align="center" prop="faceImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.faceImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="性别" align="center" prop="gender" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column width="140" label="证件号" align="center" prop="idNumber" />
      <el-table-column width="110" label="电话号码" align="center" prop="phoneNumber" />
      <el-table-column style="text-align: center" label="人员类型" width="80">
        <template slot-scope="scope">
          <span style="text-align: center" v-if="scope.row.residentTypeId==1">户籍人员</span>
          <span style="text-align: center" v-if="scope.row.residentTypeId==2">外来人员</span>
          <span style="text-align: center" v-if="scope.row.residentTypeId==3">境外人员</span>
        </template>
      </el-table-column>
      <el-table-column label="小区名称" align="center" prop="plotName" />
      <el-table-column label="身份标签" align="center" prop="identityTag" />
      <el-table-column label="户籍地址" align="center" prop="householdAddress" />
      <el-table-column style="text-align: center" label="居住状态" width="100">
        <template slot-scope="scope">
          <span style="display: inline-block; text-align: center; width: 100%;" v-if="scope.row.migrationStatus==1">迁入</span>
          <span style="display: inline-block; text-align: center; width: 100%;" v-if="scope.row.migrationStatus==2">迁出</span>
          <span style="display: inline-block; text-align: center; width: 100%;" v-if="scope.row.migrationStatus==3">常住</span>
        </template>
      </el-table-column>
      <el-table-column label="最后出现时间" align="center" prop="lastSeen" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastSeen, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="档案/布控" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="personFile(scope.row)"
          >一人一档</el-button>
          <el-button
            size="mini"
            type="text"
            @click="deployControl(scope.row)"
          >一键布控</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:residents:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:residents:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改实有人口对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="人脸照片" prop="faceImage">
          <image-upload v-model="form.faceImage"/>
        </el-form-item>
        <el-form-item label="姓名" prop="name" clearable>
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.gender">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="证件号" prop="idNumber" clearable>
          <el-input v-model="form.idNumber" placeholder="请输入证件号，如身份证号，要求唯一" @blur="handleBlur" />
        </el-form-item>
        <el-form-item label="电话号码" prop="phoneNumber" clearable>
          <el-input v-model="form.phoneNumber" placeholder="请输入电话号码" @blur="handlePhoneBlur" />
        </el-form-item>
        <el-form-item label="人员类型" prop="residentTypeId" clearable>
          <el-select v-model="form.residentTypeId" placeholder="请选择人员类型">
            <el-option label="户籍人员" value="1"></el-option>
            <el-option label="外来人员" value="2"></el-option>
            <el-option label="境外人员" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="小区名称" prop="plotId" clearable>
          <el-select v-model="form.plotId" placeholder="请选择小区">
            <el-option v-for="i in plotList" :key="i.id" :label="i.plotName" :value="i.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份标签" prop="identityTag">
          <el-select v-model="form.identityTag" placeholder="全部" clearable>
            <el-option
              v-for="dict in dict.type.personnel_tag"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="户籍地址" prop="householdAddress">
          <el-input v-model="form.householdAddress" placeholder="请输入户籍地址" />
        </el-form-item>
        <el-form-item label="居住状态" prop="householdAddress">
          <el-select v-model="form.migrationStatus" placeholder="全部" clearable>
            <el-option
              v-for="dict in dict.type.habitability"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出现时间" prop="lastSeen">
          <el-date-picker clearable
            v-model="form.lastSeen"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择最后出现时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listResidents,
  getResidents,
  delResidents,
  addResidents,
  updateResidents,
  getResidentsByIdNumber
} from "@/api/system/residents";
import {listPlots} from "@/api/system/smart/plot";

export default {
  name: "Residents",
  dicts: ['personnel_category','sys_user_sex','personnel_tag','habitability'],
  data() {
    return {
      isAdvancedSearch: false,
      iconClass: {
        type: String,
        default: 'el-icon-s-data',
      },
      plotList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 实有人口表格数据
      residentsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        resident: '',
        residentTypeId: '',
        plotId: '',
        identityTag: '',
        householdAddress: '',
        minAge: '',
        maxAge: ''
      },
      // 表单参数
      form: {
        residentTypeId: null,
        migrationStatus: null
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "change" }
        ],
        idNumber: [
          { required: true, message: "证件号，如身份证号，要求唯一不能为空", trigger: "blur" }
        ],
        residentTypeId: [
          { required: true, message: "人员类型，1-户籍人员，2-外来人员，3-境外人员不能为空", trigger: "blur" }
        ],
        plotId: [
          { required: true, message: "小区名称", trigger: "blur" }
        ],
        migrationStatus: [
          { required: true, message: "迁入迁出状态，1-迁入，2-迁出，3-常住不能为空", trigger: "change" }
        ],
      },
      userId: 0,
      user: {}
    };
  },
  created() {
    this.user = JSON.parse(sessionStorage.getItem('user'))
    this.getList();
    this.getPlotList();
  },
  methods: {
    // 验证手机号
    handlePhoneBlur() {
      // 示例：验证手机号的格式
      const isValidPhoneNumber = (phoneNumber) => {
        // 示例：验证手机号的格式
        const phoneNumberRegex = /^1[3456789]\d{9}$/;
        return phoneNumberRegex.test(phoneNumber);
      };
      if (!isValidPhoneNumber(this.form.phoneNumber)) {
        this.$message.error('请输入有效的手机号码！');
        return;
      }
    },
    // 验证证件号
    handleBlur() {
      // 示例：验证证件号的格式
      const isValidIdNumber = (idNumber) => {
        // 示例：验证证件号的格式
        const idNumberRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
        return idNumberRegex.test(idNumber);
      };
      if (!isValidIdNumber(this.form.idNumber)) {
        this.$message.error('请输入有效的证件号码！');
        return;
      }else {
        // 验证证件号是否已存在
        getResidentsByIdNumber(this.form.idNumber).then(res=>{
          if(res.data == null) {
            if (this.form.idNumber.substr(16, 1) % 2 == 0) {
              this.form.gender = '女';
            } else {
              this.form.gender = '男';
            }
          } else {
            // 根据证件号的第17位是奇数还是偶数
            this.$message.error('该证件号已存在！');
            return;
          }
        })
      }
    },
    personFile(row) {
      this.$router.push({ path: '/community/archivess/residents', query: { residents: row } });
    },
    deployControl() {
      this.$router.push('/community/alarm/task');
    },
    getPlotList() {
      this.userId = this.user.userId
      listPlots(this.userId).then(res=>{
        this.plotList = res.data;
      })
    },
    /** 查询实有人口列表 */
    getList() {
      this.loading = true;
      listResidents(this.queryParams).then(response => {
        console.log(response)
        this.residentsList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        faceImage: null,
        name: null,
        gender: null,
        idNumber: null,
        phoneNumber: null,
        residentTypeId: null,
        plotId: null,
        identityTag: null,
        householdAddress: null,
        migrationStatus: null,
        lastSeen: null
      };
      this.resetForm("form");
    },
    /**
     *  高级检索
     */
    advancedSearch() {
      if (this.isAdvancedSearch == true){
        this.isAdvancedSearch = false
      }else if (this.isAdvancedSearch == false){
        this.isAdvancedSearch = true
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {}
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加实有人口";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(JSON.stringify(row))
      this.reset();
      const id = row.id || this.ids
      getResidents(id).then(response => {
        this.form = response.data;
        this.form.migrationStatus = row.migrationStatus + ""
        this.form.residentTypeId = row.residentTypeId + ""
        console.log(this.form)
        this.open = true;
        this.title = "修改实有人口";
      });

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateResidents(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addResidents(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除实有人口编号为"' + ids + '"的数据项？').then(function() {
        return delResidents(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/residents/export', {
        ...this.queryParams
      }, `residents_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.custom-button {
  border: none; /* 移除边框 */
  background-color: transparent; /* 移除背景色 */
  color: inherit; /* 继承父元素颜色 */
  padding: 0; /* 移除内边距 */
}

.custom-button .el-icon-s-data {
  display: none; /* 隐藏图标 */
}

.custom-button span {
  font-size: 14px; /* 调整字体大小 */
}
</style>
